package com.deep.spring.v6;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class WeatherDataServiceImpl implements WeatherDataService {

    private static final String WEATHER_API = "http://wthrcdn.etouch.cn/weather_mini";

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public WeatherResponse getDataByCityId(String cityId) {
        String uri = WEATHER_API + "?citykey=" + cityId;

        return this.doGetWeatherData(uri);
    }

    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        String uri = WEATHER_API + "?city=" + cityName;

        return this.doGetWeatherData(uri);
    }

    private WeatherResponse doGetWeatherData(String url) {
        ResponseEntity<String> response
                = restTemplate.getForEntity(url, String.class);
        String strBody = null;

        if (response.getStatusCodeValue() == 200) {
            try {
                strBody = response.getBody();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        ObjectMapper mapper = new ObjectMapper();
        WeatherResponse weather = null;

        try {
            weather = JSON.parseObject(strBody, WeatherResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return weather;
    }
}
